package com.xyulu.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyulu.dao.BlogCommentsDao;
import com.xyulu.entity.BlogCommentsEntity;
import com.xyulu.service.BlogCommentsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lumin
 * @since 2021-02-25
 */
@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsDao, BlogCommentsEntity> implements BlogCommentsService {

    //存放迭代找出的所有子代的集合
    private List<BlogCommentsEntity> tempReplys = new ArrayList<>();

    @Override
    public List<BlogCommentsEntity> handleComments(List<BlogCommentsEntity> parents) {

        List<BlogCommentsEntity> firstChilds = null;
        //遍历顶级评论
        for (BlogCommentsEntity comment : parents) {
            //获取一级回复
            if (getReplyCount(comment) > 0){
                firstChilds = listChilds(comment.getId());
                //处理二级回复
                for (BlogCommentsEntity child : firstChilds) {
                    child.setParentUserName(comment.getUsername());
                    handleChildComments(child);
                }
                comment.setReplyComments(tempReplys);
                tempReplys = new ArrayList<>();
            }
        }
        return parents;
    }

    private Integer getReplyCount(BlogCommentsEntity comment) {
        Integer count = 0;
        try {
            count = count(Wrappers.<BlogCommentsEntity>lambdaQuery()
                    .eq(BlogCommentsEntity::getReplyTo, comment.getId()));
            comment.setReplyNum(count);
        } catch (Exception e) {
            log.error("获取当前评论回复数失败",e);
        }
        return count;
    }

    private List<BlogCommentsEntity> listChilds(Integer id) {
        return baseMapper.listChilds(id);
    }

    @Override
    public void AddReplyNum(Integer id) {
        baseMapper.AddReplyNum(id);
    }

    private void handleChildComments(BlogCommentsEntity parent) {
        tempReplys.add(parent);
        List<BlogCommentsEntity> childs = null;
        if (getReplyCount(parent) > 0) {
            childs = listChilds(parent.getId());
            for (BlogCommentsEntity child : childs) {
                child.setParentUserName(parent.getUsername());
                tempReplys.add(child);
                if (getReplyCount(child) > 0) {
                    handleChildComments(child);
                }
            }
        }
    }


    @Override
    public List<BlogCommentsEntity> listComments(Integer blogId) {
        return baseMapper.listComments(blogId);
    }

}
